<template>
    <div ref="chartBoxRef" style="height: 100%; width: 100%"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref, watch } from 'vue'
import { CEventEnum } from '~/enum/CEventEnum'
import System from '~/utils/System'
export default defineComponent({
    props: {
        data: {
            default: {
                xAxisData: [],
                yAxisData: []
            } as any
        },
        buildOption: {
            default: (() => {}) as Function
        },
        clear: {
            default: false
        },
        resize: {
            default: false
        }
    },
    emits: ['finished'],
    setup(props, { emit }) {
        watch(
            () => props.data,
            () => {
                initChart()
            }
        )

        const chartBoxRef = ref<HTMLDivElement>(null as any)
        let chart: echarts.EChartsType

        const resizeObj = DomUtil.listener(window, 'resize', (event: any) => {
            setTimeout(() => {
                chart?.resize()
            }, 50)
        })
        const initChart = () => {
            if (chart === undefined) chart = System.echarts.init(chartBoxRef.value as any)
            if (props.clear) chart.clear()
            if (props.data) {
                const option = props.buildOption(props.data)

                chart.on('finished', () => {
                    emit('finished')
                })

                chart.setOption(option)

                if (props.resize) {
                    setTimeout(() => {
                        chart?.resize()
                    }, 50)
                }
            }
        }

        let cid = null as any

        onMounted(() => {
            initChart()
            cid = CEvent.on(CEventEnum.changeTheme, () => {
                initChart()
            })
        })

        onUnmounted(() => {
            CEvent.off(cid)
            resizeObj.remove()
            if (chart) chart.dispose()
        })

        return { chartBoxRef }
    }
})
</script>
<style lang="less" scoped></style>
